<?php

namespace App\Http\Controllers\home;

use App\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Msg;
use App\User;

class MsgController extends Controller
{
   

    // vue用户用户发布问题
    public function create(Request $request){

        $token = $request->bearerToken();
        $user = User::where("token",$token)->first();
        
        $msg = new Msg();
        $msg->question = $request->question;
        $res = $msg->save();
        if($res){
            return response()->json(['meta'=>['status'=>200,'msg'=>'消息发布成功'],'data'=>$msg]);
        }else{
            return response()->json(['meta'=>['status'=>3000,'msg'=>'消息发布失败'],'data'=>$msg]);
        }

    }


    // 小程序用户发布问题
    public function save(Request $request){

        // 1 获取登录用户
        $token = $request->bearerToken();
        $user = User::where("api_token",$token)->first();

        // 2 获取openid;
        $uid = $user->id;

        // 3 保存数据;
        $msg = new Msg();
        $msg->uid = $uid;
        $msg->question = $request->question;
        $res = $msg->save();

        // 4 反馈
        if($res){
            return response()->json(['msg'=>"消息保存成功!",'status'=>200]);
        }else{
            return response()->json(['msg'=>"消息保存失败!",'status'=>3000]);
        }

    }

    // 管理员回复问题
    public function msg_answer(Request $request){

        // 3 保存数据;
        $msg = Msg::find($request->id);
        $msg->answer  = $request->answer;

        $res = $msg->save();

        // 4 反馈
        if($res){
            return response()->json(['meta'=>['status'=>200,'msg'=>'回复成功!'],'data'=>$msg]);
        }else{
            return response()->json(['meta'=>['status'=>3000,'msg'=>'回复失败!'],'data'=>$msg]);
        }
          
    }


    // 用户获取自己的消息列表
    public function msgs(Request $request){

        // 1 获取登录用户
        $token = $request->bearerToken();

        $user = User::where("api_token",$token)->first();

        // 2 获取openid;
        $uid = $user->id;

       // 3 获取分页数据;
       $msgs = Msg::where("uid",$uid)->orderBy("created_at",'desc')->paginate(5);
      
       // 4 返回消息;
       return $msgs;
       
    }

    // 管理员获取所有用户的消息
    public function msg_list(Request $request){
    
        $msgs = Msg::orderBy("created_at",'desc')->paginate($request->size);
        return response()->json(['meta'=>['status'=>200,'msg'=>'获取消息成功'],'data'=>$msgs]);
       
     }
     

    
}
